package com.tools.demo.map;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tools.demo.login.LoginBody;
import com.tools.demo.login.secret.RsaPrivateKey;
import com.tools.demo.login.secret.SecretKey;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 登录验证
 * 
 * @author mfk
 */
@RestController
public class MapController
{
    String MAP_URL = "http://172.18.66.90:9090/CityMap/3D-qsyjzbm/rest";
    String MAP_URL2 = "http://www.supermapol.com/realspace/services/3D-ZF_normal/rest/realspace";
    String access_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcHBJZCI6InNhY2FfNnZLNzMyOUFnciIsImlzcyI6ImdhdGV3YXkiLCJleHAiOjE3MDIxMjU0MzEsImlhdCI6MTcwMjAzOTAzMSwianRpIjoiOTQ2YmZiYmEtMmRlZi00YTZkLThjMWMtOTZkYmZlNjIzYWFkIn0.zQSwf4j9MWvc5YU5Ncynfot06YQ9CsTVPzyKphoBoBA";

    String token = "Hy_oA4Gtsm7l7bj43Rqa6JTtSPewQ-OJ4bIvculNASIGcPyCFAiXvHN66f1C0OQFrid9HqVFvCIVvDWqmXvYOQ..";

    private static final Logger logger = LoggerFactory.getLogger(MapController.class);

    /**
     * 通讯基础地址
     */
//    private String commBaseUrl = "http://www.supermapol.com";
    private String commBaseUrl = "http://172.18.66.90:9090";

    @GetMapping("/CityMap/**")
    public ResponseEntity<String> CityMap(HttpServletRequest request){

        return getTransfer(request, "token", token);

    }

    private ResponseEntity getTransfer(HttpServletRequest request, String... queryParams) {
        Map<String, String> headers = new HashMap<>();
        headers.put("authoritytype", "2");
        headers.put("access_token", access_token);
        headers.put("testmarker", "1");
        headers.put("hearbeat", "1");
        headers.put("elementsVersion", "1.00");

        String servletPath = request.getServletPath();

        //取出查询参数字符串
        String queryString = getQueryString(request);

        //组装请求url，{通讯基础地址}{servletPath}?{查询参数字符串}&{附加查询参数key}={附加查询参数value}...
        StringBuilder reqUrlStringBuilder = new StringBuilder(commBaseUrl).append(servletPath);
        reqUrlStringBuilder.append("?").append(queryString);


        //遍历附加的查询参数，将他们也组装到请求url中
        for (int i = 0; i < queryParams.length; i++) {
            reqUrlStringBuilder.append("&").append(queryParams[i++]).append("=").append(queryParams[i]);
        }

        String reqUrl = reqUrlStringBuilder.toString();
        System.out.println("reqUrl: " + reqUrl);

        //与地图服务进行通讯，get方式，获取应答
//        HttpResponse mapResponse = HttpUtil.createGet(reqUrl)
//                .headerMap(headers, true)
//                .execute();
        String res =  HttpUtil.createGet(reqUrl)
                .headerMap(headers, true)
                .execute()
                .body();

        //取出应答的状态码
//        int resStatus = mapResponse.getStatus();        //状态码
//        System.out.println("resStatus: " + resStatus);

        //将地图服务的应答数据，应答头，应答码原样返回
//        return new ResponseEntity(mapResponse.bodyBytes(), getResHeaders(mapResponse), resStatus);
        String resResult = res.replaceAll("supermap.cz.cn:8090",
                "localhost:8080")
                .replaceAll("/iserver/services/3D-qsyjzbm/rest",
                        "/CityMap/3D-qsyjzbm/rest");
        System.out.println(resResult);
        MultiValueMap<String, String> h = new LinkedMultiValueMap<>();
        h.add("Content-Type", "text/html");
        return new ResponseEntity(resResult, h, HttpStatus.OK);
    }

    /**
     * 从http请求出取出查询参数字符串
     * @param request http请求
     * @return 查询参数字符串
     */
    private String getQueryString(HttpServletRequest request) {
        //开始组装查询参数字符串
        StringBuilder queryStringBuilder = new StringBuilder();

        //遍历请求中的参数，挨个组装
        Enumeration<String> parameterNames = request.getParameterNames();
        while ((parameterNames.hasMoreElements())) {
            String parameterName = parameterNames.nextElement();
            String parameterValue = request.getParameter(parameterName);
            queryStringBuilder.append("&").append(parameterName).append("=").append(parameterValue);
        }

        if (queryStringBuilder.length() > 0) {      //如果长度大于0，删除第一个&符号
            queryStringBuilder.delete(0, 1);
        }

        //处理完成后返回
        return queryStringBuilder.toString();
    }

    /**
     * 从地图服务的http应答头中取出返回给前台的http应答头
     * @param mapResponse 和地图服务通讯后的http应答
     * @return 返回给前台的http应答头
     */
    private HttpHeaders getResHeaders(HttpResponse mapResponse) {
        HttpHeaders resHeaders = new HttpHeaders();

        //取出地图服务的应答头，对其进行遍历，原样塞入http应答头
        Map<String, List<String>> mapResHeaders = mapResponse.headers();
        for (Map.Entry<String, List<String>> entry : mapResHeaders.entrySet()) {
            String key = entry.getKey();
            if (key == null) {      //key为null的情况，不处理直接跳过
                continue;
            }
            resHeaders.add(key, entry.getValue().get(0));
        }

        return resHeaders;
    }


}
